package css.sword.annotation;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;


/**
 * 
 *
 * @project 深圳OA
 * @package com.css.bussiness.exception.utils
 * @file OAGyUtils.java 创建时间:2017年2月14日下午1:06:01
 * @title 标题（要求能简洁地表达出类的功能和职责）
 * @description 描述（简要描述类的职责、实现方式、使用注意事项等）
 * @copyright Copyright (c) 2017 中国软件与技术服务股份有限公司
 * @company 中国软件与技术服务股份有限公司
 * @module 模块: 模块名称
 * @author 史雪涛
 * @reviewer 审核人
 * @version 1.0
 * @history 修订历史（历次修订内容、修订人、修订时间等）
 *
 */
public class WebAopTool {

    /**线程池*/
    static ExecutorService pool=Executors.newFixedThreadPool(10);
    /**
     * 错误日志
     */
    static Logger logger = LoggerFactory.getLogger(WebAopTool.class);
    /**
     * 时间格式化工具
     */
    static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    static LinkedList<String> serviceNameContainer = new LinkedList<String>();

    static Map<String, LinkedList<String>> conMap = new ConcurrentHashMap<String, LinkedList<String>>();


    
    /**
     * 保存到es中
     *@name    中文名称
     *@description 相关说明
     *@time    创建时间:2018年10月11日上午10:40:43
     *@param map 传入参数
     *@throws Exception
     *@author   史雪涛
     *@history 修订历史（历次修订内容、修订人、修订时间等）
     */
    public static void saveLog2ES(Map<String, Object> map) {
        try {
                final String topics="soafile";
                OAkafka.sendkafka(map,topics);
        } catch (Exception e) {          
            e.printStackTrace();
        }
    }

        public static void setAopStackParentServiceName( String sessionId,String serviceName){


        LinkedList<String> serviceNameList = getServiceNameContainer(sessionId);

        if (serviceNameList==null) {
            serviceNameList = new LinkedList<String>();
        }
        serviceNameList.add(serviceName );
        putServiceNameContainer(sessionId, serviceNameList);
    }
    public static void putServiceNameContainer( String sessionId,LinkedList<String> serviceNameList){
        serviceNameContainer = serviceNameList;
        conMap.put(sessionId,serviceNameList);

    }
    public static String getParentServiceNameContainer(String sessionId){
        String parentServiceName = "null";
        LinkedList<String> serviceNameList = conMap.get(sessionId);
        if (null==serviceNameList || serviceNameList.size() < 2) {
            return parentServiceName;
        }

         serviceNameList.removeLast();
         parentServiceName = serviceNameList.get(serviceNameList.size() - 1);
        return parentServiceName;
    }
    public static LinkedList<String>  getServiceNameContainer(String sessionId){
        LinkedList<String> serviceNameList = conMap.get(sessionId);
        return serviceNameList;

    }


    /**
     * 
     *@name    中文名称
     *@description 相关说明
     *@time    创建时间:2018年10月18日上午9:42:47
     *@param map map
     *@author   史雪涛
     *@history 修订历史（历次修订内容、修订人、修订时间等）
     */
    public static void sysoutmap(Map<String, Object> map) {
        final String sessionId = (String) map.get("session_id");
        final String parentsessionId = (String) map.get("parent_session_id");
        final String serviceName = (String) map.get("servicename");
        final String reqData = (String) map.get("reqdata");
        final String resData = (String) map.get("resdata");
        final String identityId = (String) map.get("identity_id");
        final String deptId = (String) map.get("dept_id");
        final Long end = (Long) map.get("end_time");
        final Long msel = (Long) map.get("msel");
        final Long start_time = (Long) map.get("start_time");
        final String exception = (String) map.get("exception");
        final String lrrq = (String) map.get("lrrq");
        System.out.println("session_id:" + sessionId);
        System.out.println("parent_session_id:" + parentsessionId);
        System.out.println("servicename:" + serviceName);
        System.out.println("reqdata:" + reqData);
        System.out.println("resdata:" + resData);
        System.out.println("start_time:" + start_time);
        System.out.println("end_time:" + end);
        System.out.println("msel:" + msel);
        System.out.println("identity_id:" + identityId);
        System.out.println("dept_id:" + deptId);
        System.out.println("lrrq:" + lrrq);
        System.out.println("exception:" + exception);
        System.out.println("**************************" + serviceName + "********************************");
    }
    /**
     * 将字符串写入到文件中
     */
    public  static void write(File file, String content) {
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(file, true)));
            out.write(content+"\r\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static String getLocalHostLANAddress() {
        try {
            InetAddress candidateAddress = null;
            // 遍历所有的网络接口
            for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
                NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
                // 在所有的接口下再遍历IP
                for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) {
                    InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                    if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
                        if (inetAddr.isSiteLocalAddress()) {
                            // 如果是site-local地址，就是它了

                            return   inetAddr.getHostAddress();
                        } else if (candidateAddress == null) {
                            // site-local类型的地址未被发现，先记录候选地址
                            candidateAddress = inetAddr;
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                return candidateAddress.getHostAddress();
            }
            // 如果没有发现 non-loopback地址.只能用最次选的方案
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            return jdkSuppliedAddress.getHostAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
